package com.hoshiibuy.company.service.impl;

import com.hoshiibuy.common.exception.CommonError;
import com.hoshiibuy.common.exception.ServiceException;

import com.hoshiibuy.company.feign.IdGeneratorService;
import com.hoshiibuy.company.mapper.ISettlementMapper;
import com.hoshiibuy.company.entity.Settlement;
import com.hoshiibuy.company.service.ISettlementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 结算方式 服务实现类
 * </p>
 *
 * @author WGJ
 * @since 2019-04-22
 */
@Service
public class SettlementServiceImpl extends ServiceImpl<ISettlementMapper, Settlement> implements ISettlementService {
    @Autowired
    private IdGeneratorService idGeneratorService;

    /**
     * @param id
     * @return com.hoshiibuy.company.entity.Settlement
     * @description: 根据id查询结算方式信息
     */
    @Cacheable(cacheNames = "settlement", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Override
    public Settlement getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * @param
     * @return boolean
     * @description: 新增结算方式
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "settlement", allEntries = true)
    @Override
    public boolean save(Settlement entity) {

        String id = idGeneratorService.queryGeneratorId();

        if (id == null) {
            throw new ServiceException(CommonError.error("新增结算方式失败"));
        }
        entity.setId(Long.parseLong(id));
        entity.setModifiedtime(LocalDateTime.now());
        entity.setCreatedtime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增结算方式失败"));
        }
        return true;
    }

    /**
     * @param settlement
     * @return boolean
     * @description: 修改结算方式信息
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "settlement", allEntries = true)
    @Override
    public boolean updateById(Settlement settlement) {

        settlement.setModifiedtime(LocalDateTime.now());
        int row = baseMapper.updateById(settlement);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改结算方式失败"));
        }
        return true;
    }
}
